package com.sina.shop.manage.controller.storage;

import com.sina.shop.core.exception.server.UpdateException;
import com.sina.shop.util.DateUtils;
import com.sina.shop.web.BaseController;
import com.sina.shop.domain.carousel.Carousel;
import com.sina.shop.manage.form.StorageForm;
import com.sina.shop.manage.service.carousel.CarouselManageService;
import com.sina.shop.manage.storage.CloudStorageException;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import static com.sina.shop.util.FileUploadUtils.uploadToTemp;
import static com.sina.shop.util.FileUtils.deleteFile;

/**
 * 云存储
 */
@Controller("storageCarouselController")
@RequestMapping("storageCarousel")
public class StorageCarouselController extends BaseController implements ServletContextAware {


    private ServletContext servletContext;

    @Autowired
    @Qualifier("carouselManageService")
    private CarouselManageService carouselManageService;

    @Autowired
    @Qualifier("sinaStorageCarouselManager")
    private SinaStorageCarouselManager sinaStorageCarouselManager;

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }


    @RequestMapping(value = "carousel/upload", method = RequestMethod.GET)
    public ModelAndView uploadView() {
        ModelAndView mv = new ModelAndView("storage/uploadCarousel");

        String pertten = DateUtils.LocalDateFormatter("yyyyMMdd");

        mv.addObject("pertten", "http://sinacloud.net/finance-documents/" + pertten);

        return mv;
    }

    @RequestMapping(value = "carousel/upload", headers = {"Content-Type=multipart/form-data"}
            , method = RequestMethod.POST)
    public ModelAndView documentUpload(@Valid StorageForm form) {

        LOG.info("form:{}", form.getDirectory());

        ModelAndView mv = new ModelAndView("resultView");
        Map<String, Object> result = new HashMap<>(5);
        File destFile = null;
        Carousel carousel = null;
        try {
            destFile = uploadToTemp(servletContext, form.getFile());

            LOG.debug("file[{}] temp to file path : {}", form.getFile().getOriginalFilename(), destFile);

            // 上传到 新浪云
            carousel = sinaStorageCarouselManager.uploadCarousel(form, destFile);

            //添加上传者
            String name = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
            carousel.setName(name);

            //数据库添加  出现异常则添加失败。
            try {
                carouselManageService.saveCarousel(carousel);
                result.put(STATUS, Boolean.TRUE);
                result.put(MSG, "上传成功");
            } catch (UpdateException e) {
                try {
                    sinaStorageCarouselManager.deleteCarousel(carousel);
                } catch (CloudStorageException c) {

                }
                result.put(STATUS, Boolean.FALSE);
                result.put(MSG, e.getMessage());
            }
        } catch (Exception e) {
            result.put(STATUS, Boolean.FALSE);
            result.put(MSG, e.getMessage());
        } finally {
            deleteFile(destFile);
        }
        mv.addObject(RESULT, result);
        return mv;
    }

    @RequestMapping(value = "carousel/download", method = RequestMethod.GET)
    public ModelAndView carouselDownload(@Valid Carousel carousel, HttpServletResponse response) {

        ModelAndView mv = new ModelAndView("resultView");
        Map<String, Object> result = new HashMap<>(4);

        carousel = carouselManageService.get(Carousel.class, carousel.getId());

        if (carousel == null) {
            result.put(STATUS, Boolean.FALSE);
            result.put(MSG, "下载失败，文件不存在");
            mv.addObject(RESULT, result);
            return mv;
        }

        try {
            response.setHeader("Content-Disposition",
                    "attachment;Filename=" + URLEncoder.encode(carousel.getOriginalFileName(), "UTF-8")
            );
            // 从新浪云下载
            sinaStorageCarouselManager.download(carousel, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response.getOutputStream() != null) {
                    response.getOutputStream().close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return mv;
    }

    @RequestMapping(value = "carousel/delete", method = RequestMethod.GET)
    public ModelAndView carouselDelete() {

        ModelAndView mv = new ModelAndView("resultView");
        Map<String, Object> result = new HashMap<>(4);
        Carousel carousel = new Carousel();
        carousel.setStorageFileName("20171128/29ab9911-b741-47e2-bebf-88eb9a4abc93.txt");

        try {
            sinaStorageCarouselManager.deleteCarousel(carousel);
            result.put(STATUS, Boolean.TRUE);
            result.put(MSG, "删除成功");
        } catch (CloudStorageException e) {
            result.put(STATUS, Boolean.FALSE);
            result.put(MSG, "删除失败");
        }
        mv.addObject(RESULT, result);

        return mv;
    }

}
